package com.hzt.agprosaleplatform.websocket;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatWebSocketHandler extends TextWebSocketHandler {
    
    // 存储在线用户会话，key为用户ID
    private static final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();
    
    // 存储用户配对关系，key为客服ID，value为用户ID
    private static final Map<String, String> chatPairs = new ConcurrentHashMap<>();
    
    // 存储用户信息
    private static final Map<String, UserInfo> userInfo = new ConcurrentHashMap<>();
    
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = getUserIdFromSession(session);
        String userType = getUserTypeFromSession(session);
        
        if (userId != null && userType != null) {
            userSessions.put(userId, session);
            userInfo.put(userId, new UserInfo(userId, userType, session));
            
            // 广播用户上线消息
            broadcastUserStatus(userId, userType, "online");
            
            // 如果是管理员，发送当前在线用户列表
            if ("admin".equals(userType)) {
                sendOnlineUsersToAdmin(session);
            }
        }
    }
    
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String userId = getUserIdFromSession(session);
        String userType = getUserTypeFromSession(session);
        
        if (userId == null || userType == null) {
            return;
        }
        
        try {
            JSONObject messageObj = JSON.parseObject(message.getPayload());
            String type = messageObj.getString("type");
            
            switch (type) {
                case "chat":
                    handleChatMessage(userId, userType, messageObj);
                    break;
                case "join":
                    handleJoinMessage(userId, userType, messageObj);
                    break;
                case "endChat":
                    handleEndChatMessage(userId, messageObj);
                    break;
            }
        } catch (Exception e) {
            System.err.println("处理消息错误: " + e.getMessage());
        }
    }
    
    private void handleChatMessage(String senderId, String senderType, JSONObject message) {
        String content = message.getString("content");
        String targetUserId = message.getString("targetUserId");
        
        JSONObject chatMessage = new JSONObject();
        chatMessage.put("type", "chat");
        chatMessage.put("userId", senderId);
        chatMessage.put("userType", senderType);
        chatMessage.put("content", content);
        chatMessage.put("timestamp", System.currentTimeMillis());
        
        if ("admin".equals(senderType) && targetUserId != null) {
            // 管理员发送给特定用户
            sendMessageToUser(targetUserId, chatMessage);
            // 也发送给管理员自己
            sendMessageToUser(senderId, chatMessage);
        } else if ("user".equals(senderType)) {
            // 用户发送给所有在线管理员
            sendMessageToAllAdmins(chatMessage);
            // 也发送给用户自己
            sendMessageToUser(senderId, chatMessage);
        }
    }
    
    private void handleJoinMessage(String userId, String userType, JSONObject message) {
        // 用户加入聊天
        JSONObject joinMessage = new JSONObject();
        joinMessage.put("type", "userJoined");
        joinMessage.put("userId", userId);
        joinMessage.put("userType", userType);
        joinMessage.put("timestamp", System.currentTimeMillis());
        
        // 通知所有管理员有新用户加入
        sendMessageToAllAdmins(joinMessage);
    }
    
    private void handleEndChatMessage(String adminId, JSONObject message) {
        String targetUserId = message.getString("targetUserId");
        
        // 结束与用户的对话
        JSONObject endMessage = new JSONObject();
        endMessage.put("type", "system");
        endMessage.put("content", "客服已结束对话");
        endMessage.put("timestamp", System.currentTimeMillis());
        
        sendMessageToUser(targetUserId, endMessage);
        
        // 从在线列表中移除用户
        userSessions.remove(targetUserId);
        userInfo.remove(targetUserId);
        
        // 通知所有管理员用户已离开
        JSONObject leaveMessage = new JSONObject();
        leaveMessage.put("type", "userLeft");
        leaveMessage.put("userId", targetUserId);
        leaveMessage.put("timestamp", System.currentTimeMillis());
        
        sendMessageToAllAdmins(leaveMessage);
    }
    
    private void broadcastUserStatus(String userId, String userType, String status) {
        JSONObject statusMessage = new JSONObject();
        statusMessage.put("type", "userJoined");
        statusMessage.put("userId", userId);
        statusMessage.put("userType", userType);
        statusMessage.put("timestamp", System.currentTimeMillis());
        
        if ("user".equals(userType)) {
            sendMessageToAllAdmins(statusMessage);
        }
    }
    
    private void sendOnlineUsersToAdmin(WebSocketSession adminSession) {
        JSONObject userListMessage = new JSONObject();
        userListMessage.put("type", "userList");
        
        // 构建用户列表
        java.util.List<Map<String, Object>> users = new java.util.ArrayList<>();
        userInfo.forEach((userId, info) -> {
            if ("user".equals(info.userType)) {
                Map<String, Object> user = new java.util.HashMap<>();
                user.put("userId", userId);
                user.put("userType", info.userType);
                user.put("userName", "用户" + userId.substring(userId.length() - 6));
                users.add(user);
            }
        });
        
        userListMessage.put("users", users);
        userListMessage.put("timestamp", System.currentTimeMillis());
        
        try {
            adminSession.sendMessage(new TextMessage(userListMessage.toJSONString()));
        } catch (IOException e) {
            System.err.println("发送用户列表失败: " + e.getMessage());
        }
    }
    
    private void sendMessageToUser(String userId, JSONObject message) {
        WebSocketSession session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message.toJSONString()));
            } catch (IOException e) {
                System.err.println("发送消息给用户失败: " + e.getMessage());
            }
        }
    }
    
    private void sendMessageToAllAdmins(JSONObject message) {
        userInfo.forEach((userId, info) -> {
            if ("admin".equals(info.userType)) {
                sendMessageToUser(userId, message);
            }
        });
    }
    
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = getUserIdFromSession(session);
        String userType = getUserTypeFromSession(session);
        
        if (userId != null) {
            userSessions.remove(userId);
            userInfo.remove(userId);
            
            // 通知其他用户该用户已离线
            JSONObject leaveMessage = new JSONObject();
            leaveMessage.put("type", "userLeft");
            leaveMessage.put("userId", userId);
            leaveMessage.put("timestamp", System.currentTimeMillis());
            
            if ("user".equals(userType)) {
                sendMessageToAllAdmins(leaveMessage);
            }
        }
    }
    
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.err.println("WebSocket传输错误: " + exception.getMessage());
    }
    
    private String getUserIdFromSession(WebSocketSession session) {
        String query = session.getUri().getQuery();
        if (query != null && query.contains("userId=")) {
            String[] params = query.split("&");
            for (String param : params) {
                if (param.startsWith("userId=")) {
                    return param.substring(7);
                }
            }
        }
        return null;
    }
    
    private String getUserTypeFromSession(WebSocketSession session) {
        String query = session.getUri().getQuery();
        if (query != null && query.contains("userType=")) {
            String[] params = query.split("&");
            for (String param : params) {
                if (param.startsWith("userType=")) {
                    return param.substring(9);
                }
            }
        }
        return null;
    }
    
    // 用户信息内部类
    private static class UserInfo {
        String userId;
        String userType;
        WebSocketSession session;
        
        UserInfo(String userId, String userType, WebSocketSession session) {
            this.userId = userId;
            this.userType = userType;
            this.session = session;
        }
    }
}